# app.py - 集成MindSpore RAG系统的Flask应用
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests
import os
import sys

# 导入自定义模块
from rag_system import RAGSystem
from api_utils import generate_answer_with_rag

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 配置参数
API_TOKEN = "sk-7d4cfaa4a511858bf032217fda8bebe6"
MODEL_NAME = 'deepseek-v3'
BASE_URL = "https://ng.115.zone/v1/"
DOC_PATH = "cangjie_doc_content.txt"

# 全局RAG系统实例
rag_system = None

def initialize_rag_system():
    """初始化RAG系统"""
    global rag_system
    try:
        rag_system = RAGSystem(DOC_PATH)
        
        # 加载文档
        if not rag_system.load_documents():
            return False
        
        # 构建索引
        if not rag_system.build_vector_index():
            return False
        
        # 初始化MindSpore模型
        rag_system.initialize_mindspore_models()
        
        print("✅ RAG系统初始化成功")
        return True
    except Exception as e:
        print(f"❌ RAG系统初始化失败: {e}")
        return False

def safe_read_file(filename):
    """安全读取文件（备用方案）"""
    try:
        with open(filename, 'r', encoding='utf-8', errors='ignore') as f:
            return f.read()
    except Exception as e:
        print(f"读取文件错误: {e}")
        try:
            with open(filename, 'r', encoding='gbk', errors='ignore') as f:
                return f.read()
        except Exception as e2:
            print(f"再次读取文件错误: {e2}")
            return "无法读取文档"

def ask_question_rag(question):
    """使用RAG系统回答问题"""
    if rag_system is None:
        return "错误：RAG系统未初始化"
    
    try:
        # 检索相关文档块
        relevant_chunks = rag_system.retrieve_relevant_chunks(question, top_k=5)
        print(f"✅ 检索到 {len(relevant_chunks)} 个相关文档块")
        
        # 生成答案
        answer = generate_answer_with_rag(question, relevant_chunks, API_TOKEN, MODEL_NAME, BASE_URL)
        
        # 使用MindSpore进行文本分析（可选）
        analysis = rag_system.process_with_mindspore(question)
        print(f"📊 MindSpore文本分析结果: {analysis}")
        
        return answer
    except Exception as e:
        return f"问答过程中出现错误: {str(e)}"

def ask_question_fallback(question):
    """备用问答函数（当RAG系统不可用时）"""
    doc_content = safe_read_file(DOC_PATH)
    if doc_content == "无法读取文档":
        return "错误：无法读取仓颉语言文档，请确保cangjie_doc_content.txt文件存在"
    
    if len(doc_content) > 5000:
        doc_content = doc_content[:5000] + "..."

    prompt = f"你是一个仓颉编程语言专家。请根据以下仓颉语言文档内容回答问题。\n\n文档内容: {doc_content}\n\n问题: {question}\n\n请提供专业、准确的回答。"

    headers = {'Authorization': f'Bearer {API_TOKEN}', 'Content-Type': 'application/json'}
    data = {
        "model": MODEL_NAME,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 1500,
        "temperature": 0.7
    }

    try:
        response = requests.post(f"{BASE_URL}chat/completions", headers=headers, json=data, timeout=60)
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content']
        else:
            return f"API错误: {response.status_code} - {response.text}"
    except Exception as e:
        return f"请求错误: {str(e)}"

# Flask路由
@app.route('/')
def index():
    """提供前端页面"""
    try:
        with open('index.html', 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        return f"前端页面未找到: {str(e)}"

@app.route('/api/chat', methods=['POST'])
def chat_api():
    """聊天API接口"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'error': '无效的JSON数据'}), 400
            
        question = data.get('question', '').strip()
        
        if not question:
            return jsonify({'success': False, 'error': '问题不能为空'}), 400
        
        print(f"收到问题: {question}")
        
        # 使用RAG系统回答问题
        if rag_system:
            answer = ask_question_rag(question)
        else:
            answer = ask_question_fallback(question)
            print("⚠️ 使用备用问答系统")
        
        return jsonify({
            'success': True,
            'answer': answer,
            'question': question,
            'method': 'rag' if rag_system else 'fallback'
        })
    except Exception as e:
        print(f"API错误: {str(e)}")
        return jsonify({
            'success': False,
            'error': f'服务器错误: {str(e)}'
        }), 500

@app.route('/api/health')
def health_check():
    """健康检查接口"""
    rag_status = "active" if rag_system else "inactive"
    return jsonify({
        'status': 'healthy', 
        'service': '仓颉AI助手',
        'version': '2.0',
        'rag_system': rag_status,
        'mindspore_integrated': True
    })

@app.route('/api/system_info')
def system_info():
    """系统信息接口"""
    if rag_system:
        doc_info = {
            'chunks_count': len(rag_system.document_chunks),
            'index_built': rag_system.tfidf_matrix is not None,
            'mindspore_initialized': rag_system.encoder is not None
        }
    else:
        doc_info = {'status': 'rag_system_not_initialized'}
    
    return jsonify({
        'system': '仓颉AI助手 with MindSpore RAG',
        'doc_info': doc_info,
        'api_config': {
            'model': MODEL_NAME,
            'base_url': BASE_URL
        }
    })

@app.route('/api/analyze', methods=['POST'])
def analyze_text():
    """文本分析接口（使用MindSpore）"""
    try:
        data = request.get_json()
        text = data.get('text', '').strip()
        
        if not text:
            return jsonify({'error': '文本不能为空'}), 400
        
        if rag_system:
            analysis = rag_system.process_with_mindspore(text)
            return jsonify({
                'success': True,
                'analysis': analysis,
                'text': text[:100] + '...' if len(text) > 100 else text
            })
        else:
            return jsonify({
                'success': False,
                'error': 'RAG系统未初始化'
            }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

if __name__ == '__main__':
    print("=" * 50)
    print("🚀 仓颉AI助手服务启动中...")
    print("📚 集成MindSpore RAG系统")
    print("=" * 50)
    
    # 检查必要文件
    if not os.path.exists(DOC_PATH):
        print(f"⚠️ 警告: 未找到{DOC_PATH}文件")
        print("请确保仓颉语言文档文件存在")
    
    # 初始化RAG系统
    print("初始化RAG系统中...")
    if not initialize_rag_system():
        print("⚠️ RAG系统初始化失败，将使用备用问答模式")
    
    print("访问地址: http://localhost:5000")
    print("API健康检查: http://localhost:5000/api/health")
    print("=" * 50)
    
    app.run(host='0.0.0.0', port=5000, debug=True)